package vertx;

import org.vertx.java.core.AsyncResult;
import org.vertx.java.core.AsyncResultHandler;
import org.vertx.java.core.Handler;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.logging.Logger;
import org.vertx.java.core.net.NetServer;
import org.vertx.java.core.net.NetSocket;
import org.vertx.java.core.streams.Pump;
import org.vertx.java.platform.Verticle;

public class ServerTcp extends Verticle {

	Logger logger = null;

	public void start() {
		logger = container.logger();
		NetServer server = (NetServer) vertx.createNetServer();
		
		((NetServer) server).connectHandler(new Handler<NetSocket>() {
			public void handle(final NetSocket socket) {
				// simile a write(buffer)
				// Pump.createPump(socket, socket).start();
				logger.info("Connection from " + socket.remoteAddress());
				
				socket.dataHandler(new Handler<Buffer>() {
		            public void handle(Buffer buffer) {
		                logger.info("I received " + buffer.length() + " bytes of data");
		                socket.write(buffer);
		            }
		        });
				
		        socket.closeHandler(new Handler<Void>() {
		            public void handle(Void arg0) {
		                logger.info("The socket is now closed");
		            }
		        });

		        socket.exceptionHandler(new Handler<Throwable>() {
		            public void handle(Throwable t) {
		                logger.info("Oops, something went wrong", t);
		            }
		        });		        
			}
		});

		server.close(new AsyncResultHandler<Void>() {
		    public void handle(AsyncResult<Void> asyncResult) {
		        logger.info("Close succeeded? " + asyncResult.succeeded());
		    }
		});
		
		((NetServer) server).listen(1234, "localhost"
//				, new AsyncResultHandler<Void>() {
//					public void handle(AsyncResult<Void> asyncResult) {
//						logger.info("Listen succeeded? " + asyncResult.succeeded());
//						logger.info("Server TCP avviato ed in ascolto sulla porta 1234");
//					}
//				}
		);

		// registro un event bus
		EventBus eb = vertx.eventBus();
		Handler<Message> myHandler = new Handler<Message>() {
			public void handle(Message message) {
				logger.info("I received a message " + message.body());
				// System.out.println("I received a message " + message.body());
			}
		};
		eb.registerHandler("test.address", myHandler);
		logger.info("Registrato un event bus test.address");

		logger.info("Invio di un messaggio");
		eb.send("test.address", "hello world");

		long timerID = vertx.setTimer(10000, new Handler<Long>() {
			public void handle(Long timerID) {
				logger.info("test processo eseguito dopo 10 secondi");
			}
		});

	}

}